{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d95f841a-63c9-41d4-aea1-496b3d2024dd",
   "metadata": {},
   "source": [
    "<table style=\"width:100%\">\n",
    "<tr>\n",
    "<td style=\"vertical-align:middle; text-align:left;\">\n",
    "<font size=\"2\">\n",
    "Supplementary code for the <a href=\"http://mng.bz/orYv\">Build a Large Language Model From Scratch</a> book by <a href=\"https://sebastianraschka.com\">Sebastian Raschka</a><br>\n",
    "<br>Code repository: <a href=\"https://github.com/rasbt/LLMs-from-scratch\">https://github.com/rasbt/LLMs-from-scratch</a>\n",
    "<br>汉化的库: <a href=\"https://github.com/GoatCsu/CN-LLMs-from-scratch.git\">https://github.com/GoatCsu/CN-LLMs-from-scratch.git</a>\n",
    "</font>\n",
    "</td>\n",
    "<td style=\"vertical-align:middle; text-align:left;\">\n",
    "<a href=\"http://mng.bz/orYv\"><img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/cover-small.webp\" width=\"100px\"></a>\n",
    "</td>\n",
    "</tr>\n",
    "</table>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "abbd7c0d-70f8-4386-a114-907e96c950b0",
   "metadata": {},
   "source": [
    "## 使用滑动窗口进行数据采样"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0ed23175-41be-4a7e-8c45-1f100b35a1a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "from importlib.metadata import version\n",
    "import torch\n",
    "\n",
    "print(\"torch version:\", version(\"torch\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92ac652d-7b38-4843-9fbd-494cdc8ec12c",
   "metadata": {},
   "source": [
    "为了更直观地理解使用滑动窗口方法的数据加载器，我们可以考虑一个仅由数字组成的数据集：\n",
    "\n",
    "```\n",
    "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 ... 1000\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "0e3f5d3c-95fe-42b2-8051-205f7803675a",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"number-data.txt\", \"w\", encoding=\"utf-8\") as f:\n",
    "    for number in range(1001):\n",
    "        f.write(f\"{number} \")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7becae19-a5a0-4236-87d5-f5eb9b6eb045",
   "metadata": {},
   "source": [
    "接下来，我们对`token_ids`进行小的修改：不再使用分词器，而是直接从文本文件中解析整数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "74b41073-4c9f-46e2-a1bd-d38e4122b375",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "5eb30ebe-97b3-43c5-9ff1-a97d621b3c4e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from torch.utils.data import Dataset, DataLoader\n",
    "\n",
    "class GPTDatasetV1(Dataset):\n",
    "    def __init__(self, txt, tokenizer, max_length, stride):\n",
    "        self.input_ids = []\n",
    "        self.target_ids = []\n",
    "\n",
    "        # 修改\n",
    "        # token_ids = tokenizer.encode(txt, allowed_special={\"<|endoftext|>\"})\n",
    "        token_ids = [int(i) for i in txt.strip().split()]\n",
    "\n",
    "        # 使用滑动窗口将文本切分为重叠的max_length序列\n",
    "        for i in range(0, len(token_ids) - max_length, stride):\n",
    "            input_chunk = token_ids[i:i + max_length]\n",
    "            target_chunk = token_ids[i + 1: i + max_length + 1]\n",
    "            self.input_ids.append(torch.tensor(input_chunk))\n",
    "            self.target_ids.append(torch.tensor(target_chunk))\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.input_ids)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        return self.input_ids[idx], self.target_ids[idx]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "42dd68ef-59f7-45ff-ba44-e311c899ddcd",
   "metadata": {},
   "source": [
    "让我们使用批量大小为1的dataloader来测试一个上下文大小为4的LLM："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "df31d96c-6bfd-4564-a956-6192242d7579",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"number-data.txt\", \"r\", encoding=\"utf-8\") as f:\n",
    "    raw_text = f.read()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "id": "9226d00c-ad9a-4949-a6e4-9afccfc7214f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[tensor([[0, 1, 2, 3]]), tensor([[1, 2, 3, 4]])]\n"
     ]
    }
   ],
   "source": [
    "dataloader = create_dataloader_v1(raw_text, batch_size=1, max_length=4, stride=1, shuffle=False)\n",
    "\n",
    "data_iter = iter(dataloader)\n",
    "first_batch = next(data_iter)\n",
    "print(first_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "10deb4bc-4de1-4d20-921e-4b1c7a0e1a6d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[tensor([[1, 2, 3, 4]]), tensor([[2, 3, 4, 5]])]\n"
     ]
    }
   ],
   "source": [
    "second_batch = next(data_iter)\n",
    "print(second_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "85a6c312-0144-4128-8d2c-06a4dc223ff7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[tensor([[2, 3, 4, 5]]), tensor([[3, 4, 5, 6]])]\n"
     ]
    }
   ],
   "source": [
    "third_batch = next(data_iter)\n",
    "print(third_batch)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "id": "14b7ec67-083a-4b28-bcb9-f4c8e97e250e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[tensor([[996, 997, 998, 999]]), tensor([[ 997,  998,  999, 1000]])]\n"
     ]
    }
   ],
   "source": [
    "for batch in dataloader:\n",
    "    pass\n",
    "\n",
    "last_batch = batch\n",
    "print(last_batch)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1ae6d45-f26e-4b83-9c7b-cff55ffa7d16",
   "metadata": {},
   "source": [
    "现在，让我们来看一下批处理后的输入："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "id": "1916e7a6-f03d-4f09-91a6-d0bdbac5a58c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Inputs:\n",
      " tensor([[992, 993, 994, 995],\n",
      "        [996, 997, 998, 999]])\n",
      "\n",
      "Targets:\n",
      " tensor([[ 993,  994,  995,  996],\n",
      "        [ 997,  998,  999, 1000]])\n"
     ]
    }
   ],
   "source": [
    "dataloader = create_dataloader_v1(raw_text, batch_size=2, max_length=4, stride=4, shuffle=False)\n",
    "\n",
    "for inputs, targets in dataloader:\n",
    "    pass\n",
    "\n",
    "print(\"Inputs:\\n\", inputs)\n",
    "print(\"\\nTargets:\\n\", targets)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cdd66560-25d5-4800-acc1-432735dfc7d6",
   "metadata": {},
   "source": [
    "随机打乱data loader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "39dd4952-5333-45f0-9032-f93007d742b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Inputs:\n",
      " tensor([[880, 881, 882, 883],\n",
      "        [112, 113, 114, 115]])\n",
      "\n",
      "Targets:\n",
      " tensor([[881, 882, 883, 884],\n",
      "        [113, 114, 115, 116]])\n"
     ]
    }
   ],
   "source": [
    "torch.manual_seed(123)\n",
    "dataloader = create_dataloader_v1(raw_text, batch_size=2, max_length=4, stride=4, shuffle=True)\n",
    "\n",
    "for inputs, targets in dataloader:\n",
    "    pass\n",
    "\n",
    "print(\"Inputs:\\n\", inputs)\n",
    "print(\"\\nTargets:\\n\", targets)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
